package com.xyauto.uilibx.utils;

import android.graphics.Color;
import android.graphics.SweepGradient;


public class ColorUtil {

    /**
     * Colors to construct the color wheel using {@link SweepGradient}.
     */
    public static final int[] COLORS = new int[]{0xFFFF0000, 0xFFFF00FF,
            0xFF0000FF, 0xFF00FFFF, 0xFF00FF00, 0xFFFFFF00, 0xFFFF0000};

    /**
     * Calculate the color using the supplied angle.
     *
     * @param angle The selected color's position expressed as angle (in rad).
     * @return The ARGB value of the color on the color wheel at the specified
     * angle.
     */
    public static int calculateColor(float angle) {
        float unit = (float) (angle / (2 * Math.PI));
        if (unit < 0) {
            unit += 1;
        }

        if (unit <= 0) {
            return COLORS[0];
        }
        if (unit >= 1) {
            return COLORS[COLORS.length - 1];
        }

        float p = unit * (COLORS.length - 1);
        int i = (int) p;
        p -= i;

        int c0 = COLORS[i];
        int c1 = COLORS[i + 1];
        int a = ave(Color.alpha(c0), Color.alpha(c1), p);
        int r = ave(Color.red(c0), Color.red(c1), p);
        int g = ave(Color.green(c0), Color.green(c1), p);
        int b = ave(Color.blue(c0), Color.blue(c1), p);

        return Color.argb(a, r, g, b);
    }

    private static int ave(int s, int d, float p) {
        return s + Math.round(p * (d - s));
    }


    /**
     * 颜色偏转
     *
     * @param color 入射颜色
     * @param angle 偏转角度 0~360
     * @return 偏转之后的颜色
     */
    public static int colorDeviation(int color, int angle) {
        //入射角度
        if (Math.abs(angle) > 360) {
            angle = angle % 360;
        }
        if (Color.alpha(color) == 0) {
            return Color.TRANSPARENT;
        }

        float[] colors = new float[3];
        Color.colorToHSV(color, colors);

        float hue = colors[0];

        hue += angle;
        if (hue < 0) {
            hue += 360;
        } else if (hue > 360) {
            hue -= 360;
        }
        colors[0] = hue;
        return Color.HSVToColor(colors);
    }

}
